package com.zyl.longpicturebackend.config;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import io.undertow.util.StatusCodes;
import org.springframework.boot.web.embedded.undertow.UndertowBuilderCustomizer;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//
//@Configuration
//public class UndertowConfig {
//
//    @Bean
//    public ServletWebServerFactory servletContainer() {
//        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
//
////        UndertowBuilderCustomizer
//        factory.addBuilderCustomizers(builder -> {
//            // 配置HTTP重定向到HTTPS
////            builder.addHttpListener(80, "0.0.0.0", "http",
////                new HttpListenerOptions().setRedirectPort(443, "https"));
//            builder.addHttpListener(80, "0.0.0.0",
//                    new HttpHandler() {
//                        @Override
//                        public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
//                            httpServerExchange.set
//                        }
//                    });
//        });
//        return factory;
//    }
//}
@Configuration
public class UndertowConfig {

    @Bean
    public UndertowServletWebServerFactory undertowServletWebServerFactory() {
        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(443); // 设置HTTPS主端口

        // 添加HTTP监听器并配置重定向
        factory.addBuilderCustomizers(builder -> {
            builder.addHttpListener(80, "0.0.0.0")
                    .setHandler(new HttpHandler() {
                        @Override
                        public void handleRequest(HttpServerExchange exchange) throws Exception {
                            exchange.setStatusCode(StatusCodes.MOVED_PERMANENTLY);
                            exchange.getResponseHeaders().put(Headers.LOCATION,
                                    "https://" + exchange.getHostAndPort() + exchange.getRequestURI());
                            exchange.endExchange();
                        }
                    });
        });

        return factory;
    }
}
